<template>
  <div class="result-preview-container">
    <div class="page-header">
      <div class="header-left">
        <el-button type="primary" @click="goBack" plain>
          <el-icon><ArrowLeft /></el-icon> 返回清洗列表
        </el-button>
        <h2 v-if="taskInfo">{{ taskInfo.name }} 的结果预览</h2>
      </div>
      <div class="header-right">
        <el-button
          type="primary"
          @click="viewStats"
          :loading="loading.stats"
          :icon="DataAnalysis"
        >
          数据统计
        </el-button>
        <el-button
          type="success"
          @click="downloadResult"
          :loading="isDownloading"
          :icon="Download"
        >
          下载结果
        </el-button>
      </div>
    </div>

    <div class="result-content" v-loading="loading.preview">
      <!-- 工作表选择 -->
      <div class="sheet-selector" v-if="sheetNames.length > 0">
        <span class="sheet-label">工作表：</span>
        <el-select v-model="currentSheet" @change="handleSheetChange" :disabled="loading.preview">
          <el-option
            v-for="sheet in sheetNames"
            :key="sheet"
            :label="sheet"
            :value="sheet"
          />
        </el-select>
      </div>

      <!-- 顶部分页控件 -->
      <div class="pagination top-pagination" v-if="totalRows > 0">
        <el-input v-model="searchName" style="width: 200px;" placeholder="搜索商品名称" @input="handleSearch" />
        <div class="pagination-actions">
          <el-button
            type="primary"
            plain
            size="small"
            @click="handleFirstPage"
            :disabled="currentPage === 1"
          >
            首页
          </el-button>
          <el-button
            type="primary"
            plain
            size="small"
            @click="handlePrevPage"
            :disabled="currentPage === 1"
          >
            <el-icon><ArrowLeft /></el-icon> 上一页
          </el-button>
          <div class="page-info">{{ currentPage }} / {{ totalPages }}</div>
          <el-button
            type="primary"
            plain
            size="small"
            @click="handleNextPage"
            :disabled="currentPage === totalPages"
          >
            下一页 <el-icon><ArrowRight /></el-icon>
          </el-button>
          <el-button
            type="primary"
            plain
            size="small"
            @click="handleLastPage"
            :disabled="currentPage === totalPages"
          >
            末页
          </el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <div v-if="!loading.preview && headers.length > 0" class="data-table">
        <el-table
          v-loading="loading.preview"
          :data="rows"
          style="width: 100%"
          border
          stripe
          max-height="calc(100vh - 280px)"
        >
          <el-table-column
            type="index"
            label="序号"
            width="70"
            align="center"
          />
          <el-table-column
            v-for="header in headers"
            :key="header"
            :prop="header"
            :label="header"
            :width="getColumnWidth(header)"
            :sortable="isSortableColumn(header)"
            class-name="getCellClass"
          >
            <template #default="{ row }">
              <template v-if="isNumberColumn(header)">
                {{ formatNumber(row[header]) }}
              </template>
              <template v-else-if="isConfidenceColumn(header)">
                <el-progress
                  :percentage="row[header] * 100"
                  :status="getConfidenceStatus(row[header])"
                  :format="(p) => p + '%'"
                />
              </template>
              <template v-else>
                {{ row[header] }}
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-empty v-else-if="!loading.preview" description="暂无数据" />

      <!-- 底部分页控件 -->
      <div class="pagination bottom-pagination" v-if="totalRows > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100, 200, 500, 1000]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalRows"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 统计信息对话框 -->
    <el-dialog
      v-model="statsDialogVisible"
      title="结果统计分析"
      width="800px"
      destroy-on-close
    >
      <div v-loading="loading.stats">
        <template v-if="resultStats">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="基础信息" name="basic">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="任务名称">{{ resultStats.task_info?.name || '-' }}</el-descriptions-item>
                <el-descriptions-item label="总商品数">{{ resultStats.total_products || 0 }}</el-descriptions-item>
                <el-descriptions-item label="识别品牌数">{{ resultStats.identified_brands || 0 }}</el-descriptions-item>
                <el-descriptions-item label="完成时间">{{ formatDate(resultStats.task_info?.completed_at) }}</el-descriptions-item>
              </el-descriptions>
            </el-tab-pane>

            <el-tab-pane label="品牌分析" name="brands">
              <h4>品牌分布</h4>
              <el-tabs type="border-card">
                <el-tab-pane label="数据库匹配品牌">
                  <el-table
                    :data="brandInDbData"
                    stripe
                    style="width: 100%"
                    max-height="300px"
                  >
                    <el-table-column prop="brand" label="品牌" />
                    <el-table-column prop="count" label="商品数" width="100" />
                    <el-table-column prop="percentage" label="占比" width="100">
                      <template #default="{ row }">
                        {{ formatPercentage(row.percentage) }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="source" label="来源" width="150" />
                  </el-table>
                </el-tab-pane>
                <el-tab-pane label="规则匹配品牌">
                  <el-table
                    :data="brandNotInDbData"
                    stripe
                    style="width: 100%"
                    max-height="300px"
                  >
                    <el-table-column prop="brand" label="品牌" />
                    <el-table-column prop="count" label="商品数" width="100" />
                    <el-table-column prop="percentage" label="占比" width="100">
                      <template #default="{ row }">
                        {{ formatPercentage(row.percentage) }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="source" label="来源" width="150" />
                  </el-table>
                </el-tab-pane>
              </el-tabs>
            </el-tab-pane>

            <el-tab-pane label="单位与价格" name="units">
              <el-row :gutter="20">
                <el-col :span="12">
                  <h4>单位分布</h4>
                  <el-table
                    :data="unitDistributionData"
                    stripe
                    style="width: 100%"
                    max-height="300px"
                  >
                    <el-table-column prop="unit" label="单位" />
                    <el-table-column prop="count" label="商品数" width="100" />
                    <el-table-column prop="percentage" label="占比" width="100">
                      <template #default="{ row }">
                        {{ formatPercentage(row.percentage) }}
                      </template>
                    </el-table-column>
                  </el-table>
                </el-col>
                <el-col :span="12">
                  <h4>标准单位分布</h4>
                  <el-table
                    :data="standardUnitData"
                    stripe
                    style="width: 100%"
                    max-height="300px"
                  >
                    <el-table-column prop="unit" label="标准单位" />
                    <el-table-column prop="count" label="商品数" width="100" />
                    <el-table-column prop="percentage" label="占比" width="100">
                      <template #default="{ row }">
                        {{ formatPercentage(row.percentage) }}
                      </template>
                    </el-table-column>
                  </el-table>
                </el-col>
              </el-row>

              <h4>标准价格统计</h4>
              <el-table
                :data="priceStatsData"
                stripe
                style="width: 100%"
              >
                <el-table-column prop="unit" label="单位" />
                <el-table-column prop="min" label="最低价" width="120">
                  <template #default="{ row }">
                    {{ formatNumber(row.min) }}
                  </template>
                </el-table-column>
                <el-table-column prop="max" label="最高价" width="120">
                  <template #default="{ row }">
                    {{ formatNumber(row.max) }}
                  </template>
                </el-table-column>
                <el-table-column prop="mean" label="平均价" width="120">
                  <template #default="{ row }">
                    {{ formatNumber(row.mean) }}
                  </template>
                </el-table-column>
                <el-table-column prop="median" label="中位数" width="120">
                  <template #default="{ row }">
                    {{ formatNumber(row.median) }}
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>

            <el-tab-pane label="提取方式" name="extract_method" v-if="resultStats.extract_method_distribution">
              <el-row :gutter="20">
                <el-col :span="12">
                  <h4>提取方式分布</h4>
                  <el-table
                    :data="extractMethodData"
                    stripe
                    style="width: 100%"
                  >
                    <el-table-column prop="method" label="提取方式" />
                    <el-table-column prop="count" label="商品数" width="100" />
                    <el-table-column prop="percentage" label="占比" width="100">
                      <template #default="{ row }">
                        {{ formatPercentage(row.percentage) }}
                      </template>
                    </el-table-column>
                  </el-table>
                </el-col>
                <el-col :span="12">
                  <h4>不同提取方式的置信度对比</h4>
                  <el-table
                    v-if="extractMethodConfidenceStats.length > 0"
                    :data="extractMethodConfidenceStats"
                    stripe
                    style="width: 100%"
                  >
                    <el-table-column prop="method" label="提取方式" />
                    <el-table-column prop="avgConfidence" label="平均置信度" width="120">
                      <template #default="{ row }">
                        {{ formatNumber(row.avgConfidence) }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="medianConfidence" label="中位置信度" width="120">
                      <template #default="{ row }">
                        {{ formatNumber(row.medianConfidence) }}
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-empty v-else description="暂无置信度数据" />
                </el-col>
              </el-row>

              <h4>提取方式说明</h4>
              <el-descriptions :column="1" border>
                <el-descriptions-item label="规则提取 (rule)">通过规则引擎自动识别和提取，基于正则表达式和品牌数据库</el-descriptions-item>
                <el-descriptions-item label="AI提取 (ai)">通过大语言模型智能分析和提取，适用于复杂格式或低置信度数据</el-descriptions-item>
              </el-descriptions>
            </el-tab-pane>

            <el-tab-pane label="置信度分析" name="confidence" v-if="resultStats.confidence_stats">
              <el-row :gutter="20">
                <el-col :span="12">
                  <h4>置信度统计</h4>
                  <el-descriptions :column="1" border>
                    <el-descriptions-item label="最低置信度">{{ formatNumber(resultStats.confidence_stats.min) }}</el-descriptions-item>
                    <el-descriptions-item label="最高置信度">{{ formatNumber(resultStats.confidence_stats.max) }}</el-descriptions-item>
                    <el-descriptions-item label="平均置信度">{{ formatNumber(resultStats.confidence_stats.mean) }}</el-descriptions-item>
                    <el-descriptions-item label="中位置信度">{{ formatNumber(resultStats.confidence_stats.median) }}</el-descriptions-item>
                  </el-descriptions>
                </el-col>
                <el-col :span="12">
                  <h4>置信度分布</h4>
                  <el-table
                    :data="confidenceDistributionData"
                    stripe
                    style="width: 100%"
                  >
                    <el-table-column prop="level" label="置信度级别" />
                    <el-table-column prop="count" label="商品数" width="100" />
                    <el-table-column prop="percentage" label="占比" width="100">
                      <template #default="{ row }">
                        {{ formatPercentage(row.percentage) }}
                      </template>
                    </el-table-column>
                  </el-table>
                </el-col>
              </el-row>
            </el-tab-pane>
          </el-tabs>
        </template>
        <template v-else-if="!loading.stats">
          <el-empty description="没有统计数据" />
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import { ArrowLeft, ArrowRight, Download, DataAnalysis } from '@element-plus/icons-vue'
import { getResultPreview, getResultStats, downloadTaskResult } from '@/api/dataClean'
import { getBrandList } from '@/api/config'

const route = useRoute()
const router = useRouter()
const taskId = computed(() => route.params.id)

// 数据和加载状态
const loading = ref({
  preview: false,
  stats: false,
  brands: false
})
const isDownloading = ref(false)

// 预览数据
const taskInfo = ref(null)
const headers = ref([])
const rows = ref([])
const allRows = ref([])
const totalRows = ref(0)
const sheetNames = ref([])
const currentSheet = ref('')

// 品牌列表数据
const dbBrands = ref([])
const brandKeywords = ref({}) // 品牌关键词映射

// 分页参数
const currentPage = ref(1)
const pageSize = ref(20)

// 统计信息相关
const resultStats = ref(null)
const statsDialogVisible = ref(false)
const activeTab = ref('basic')

// 搜索参数
const searchName = ref('')

const handleSearch = () => {
  // fetchResultPreview()
  // 按商品名称筛选 纯前端过滤
  rows.value = allRows.value.filter(row => row['cleaned_name'].includes(searchName.value))
}

// 获取数据库品牌列表
const fetchDbBrands = async () => {
  loading.value.brands = true
  try {
    const response = await getBrandList({ pageSize: 9999 })
    dbBrands.value = response.data || []
    
    // 创建品牌关键词映射
    brandKeywords.value = {}
    dbBrands.value.forEach(brand => {
      brandKeywords.value[brand.name] = true
      if (brand.aliases) {
        const aliases = typeof brand.aliases === 'string' 
          ? brand.aliases.split(',') 
          : (Array.isArray(brand.aliases) ? brand.aliases : [])
        
        aliases.forEach(alias => {
          if (alias && alias.trim()) {
            brandKeywords.value[alias.trim()] = true
          }
        })
      }
    })
    
    console.log('加载了', Object.keys(brandKeywords.value).length, '个品牌关键词')
  } catch (error) {
    console.error('获取品牌列表失败:', error)
  } finally {
    loading.value.brands = false
  }
}

// 获取结果预览数据
const fetchResultPreview = async (sheet = null) => {
  loading.value.preview = true
  try {
    const response = await getResultPreview(taskId.value, sheet, searchName.value)
    
    // 设置预览数据
    headers.value = response.headers || []
    allRows.value = response.rows || []
    sheetNames.value = response.sheet_names || []
    currentSheet.value = response.current_sheet || ''
    totalRows.value = response.total_rows || 0
    taskInfo.value = response.task_info || null
    
    // 应用分页
    updatePageData()
  } catch (error) {
    console.error('获取结果预览失败:', error)
    ElMessage.error('获取结果预览失败')
  } finally {
    loading.value.preview = false
  }
}

// 鼠标选择文本相关功能
const selectedText = ref('')
const showContextMenu = ref(false)
const contextMenuPosition = ref({ x: 0, y: 0 })

// 监听鼠标选择事件
const handleTextSelection = () => {
  console.log('handleTextSelection')
  const selection = window.getSelection()
  if (selection.toString().trim()) {
    selectedText.value = selection.toString().trim()
    const range = selection.getRangeAt(0)
    const rect = range.getBoundingClientRect()
    
    // 设置菜单位置
    contextMenuPosition.value = {
      x: rect.left + window.scrollX,
      y: rect.bottom + window.scrollY
    }
    showContextMenu.value = true
  } else {
    showContextMenu.value = false
  }
}

// 标记为品牌
const markAsBrand = async () => {
  try {
    // 调用API标记品牌
    // await markBrand(selectedText.value)
    ElMessage.success('标记品牌成功')
    // 刷新数据
    // fetchResultPreview(currentSheet.value)
  } catch (error) {
    console.error('标记品牌失败:', error)
    ElMessage.error('标记品牌失败')
  } finally {
    showContextMenu.value = false
  }
}

// 标记为商品名称
const markAsProductName = async () => {
  try {
    // 调用API标记商品名称
    // await markProductName(selectedText.value)
    ElMessage.success('标记商品名称成功')
    // 刷新数据
    // fetchResultPreview(currentSheet.value)
  } catch (error) {
    console.error('标记商品名称失败:', error)
    ElMessage.error('标记商品名称失败')
  } finally {
    showContextMenu.value = false
  }
}

// 点击其他地方关闭菜单
const handleClickOutside = (event) => {
  if (showContextMenu.value && !event.target.closest('.context-menu')) {
    showContextMenu.value = false
  }
}

// 监听全局点击事件
onMounted(() => {
  document.addEventListener('mouseup', handleTextSelection)
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('mouseup', handleTextSelection)
  document.removeEventListener('click', handleClickOutside)
})

// 分页相关方法
const updatePageData = () => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  rows.value = allRows.value.slice(start, end)

  console.log('rows.value',start, end, allRows.value, rows.value)
}

const handleCurrentChange = (val) => {
  currentPage.value = val;
  updatePageData();
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置到第一页
  updatePageData();
};

const handlePrevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    updatePageData();
  }
};

const handleNextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
    updatePageData();
  }
};

const handleFirstPage = () => {
  currentPage.value = 1;
  updatePageData();
};

const handleLastPage = () => {
  currentPage.value = totalPages.value;
  updatePageData();
};

// 工作表切换处理
const handleSheetChange = (sheet) => {
  fetchResultPreview(sheet)
}

// 获取结果统计信息
const fetchResultStats = async () => {
  loading.value.stats = true
  try {
    const response = await getResultStats(taskId.value)
    resultStats.value = response
    
    // 如果数据库品牌尚未加载，加载它们
    if (dbBrands.value.length === 0) {
      await fetchDbBrands()
    }
    
    // 分析品牌匹配情况
    analyzeBrandMatching()
  } catch (error) {
    console.error('获取结果统计信息失败:', error)
    ElMessage.error('获取结果统计信息失败')
  } finally {
    loading.value.stats = false
  }
}

// 分析品牌匹配情况
const analyzeBrandMatching = () => {
  if (!resultStats.value || !resultStats.value.brands_in_database) return
  
  // 获取所有品牌
  const allBrands = { 
    ...resultStats.value.brands_in_database, 
    ...resultStats.value.brands_not_in_database 
  }
  
  // 分类品牌
  const dbMatchedBrands = {}
  const ruleMatchedBrands = {}
  
  Object.entries(allBrands).forEach(([brand, count]) => {
    if (brandKeywords.value[brand]) {
      dbMatchedBrands[brand] = count
    } else {
      ruleMatchedBrands[brand] = count
    }
  })
  
  // 更新结果统计中的品牌分类
  resultStats.value.db_matched_brands = dbMatchedBrands
  resultStats.value.rule_matched_brands = ruleMatchedBrands
}

// 查看统计信息
const viewStats = async () => {
  statsDialogVisible.value = true
  if (!resultStats.value) {
    await fetchResultStats()
  }
}

// 下载结果文件
const downloadResult = async () => {
  isDownloading.value = true
  try {
    await downloadTaskResult(taskId.value)
    ElMessage.success('下载成功')
  } catch (error) {
    console.error('下载结果文件失败:', error)
    ElMessage.error('下载结果文件失败')
  } finally {
    isDownloading.value = false
  }
}

// 返回列表页
const goBack = () => {
  router.push('/data-clean')
}

// 表格相关辅助方法
const getColumnWidth = (header) => {
  if (['商品名称', 'cleaned_name'].includes(header)) {
    return 200
  } else if (['brand', 'unit', 'specification'].includes(header)) {
    return 120
  } else if (['price', 'standard_price', 'standard_price2'].includes(header)) {
    return 100
  } else if (['standard_unit', 'standard_unit2'].includes(header)) {
    return 120
  } else if (['confidence_score'].includes(header)) {
    return 150
  } else if (['extract_method'].includes(header)) {
    return 100
  }
  return 120
}

const getCellClass = ({ row, column }) => {
  const header = column.property
  if (header === 'confidence_score') {
    if (row[header] >= 0.8) return 'high-confidence'
    if (row[header] >= 0.6) return 'medium-confidence'
    if (row[header] >= 0.4) return 'low-confidence'
    return 'very-low-confidence'
  }
  
  // 突出显示提取方式
  if (header === 'extract_method') {
    if (row[header] === 'rule') return 'rule-extraction'
    if (row[header] === 'ai') return 'ai-extraction'
    return ''
  }
  
  // 突出显示清洗结果列
  if (['cleaned_name', 'brand', 'specification', 'unit', 'standard_unit', 'standard_unit2', 'standard_price', 'standard_price2'].includes(header)) {
    return 'cleaned-column'
  }
  
  return ''
}

const isNumberColumn = (header) => {
  return ['price', 'standard_price', 'standard_price2'].includes(header)
}

const isConfidenceColumn = (header) => {
  return header === 'confidence_score'
}

const isSortableColumn = (header) => {
  return ['brand', 'specification', 'unit', 'standard_unit', 'standard_unit2', 'price', 'standard_price', 'standard_price2', 'confidence_score'].includes(header)
}

const getConfidenceStatus = (value) => {
  if (value >= 0.8) return 'success'
  if (value >= 0.6) return ''
  if (value >= 0.4) return 'warning'
  return 'exception'
}

// 格式化方法
const formatNumber = (num) => {
  if (num === null || num === undefined) return '-'
  return Number(num).toFixed(2)
}

const formatPercentage = (value) => {
  if (value === null || value === undefined) return '-'
  return `${(value * 100).toFixed(2)}%`
}

const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString()
}

// 统计数据计算
const brandInDbData = computed(() => {
  if (!resultStats.value?.db_matched_brands) return []
  
  const total = resultStats.value.total_products || 1
  return Object.entries(resultStats.value.db_matched_brands)
    .map(([brand, count]) => ({
      brand,
      count,
      percentage: count / total,
      source: '数据库直接匹配'
    }))
    .sort((a, b) => b.count - a.count)
})

const brandNotInDbData = computed(() => {
  if (!resultStats.value?.rule_matched_brands) return []
  
  const total = resultStats.value.total_products || 1
  return Object.entries(resultStats.value.rule_matched_brands)
    .map(([brand, count]) => ({
      brand,
      count,
      percentage: count / total,
      source: '规则识别匹配'
    }))
    .sort((a, b) => b.count - a.count)
})

const unitDistributionData = computed(() => {
  if (!resultStats.value?.units_distribution) return []
  
  const total = resultStats.value.total_products || 1
  return Object.entries(resultStats.value.units_distribution)
    .map(([unit, count]) => ({
      unit,
      count,
      percentage: count / total
    }))
    .sort((a, b) => b.count - a.count)
})

const standardUnitData = computed(() => {
  if (!resultStats.value?.standard_units_distribution) return []
  
  const total = resultStats.value.total_products || 1
  let combinedUnits = { ...resultStats.value.standard_units_distribution }
  
  // 添加标准单位2的分布
  if (resultStats.value?.standard_units2_distribution) {
    Object.entries(resultStats.value.standard_units2_distribution).forEach(([unit, count]) => {
      if (combinedUnits[unit]) {
        combinedUnits[unit] += count
      } else {
        combinedUnits[unit] = count
      }
    })
  }
  
  return Object.entries(combinedUnits)
    .map(([unit, count]) => ({
      unit,
      count,
      percentage: count / total
    }))
    .sort((a, b) => b.count - a.count)
})

const priceStatsData = computed(() => {
  if (!resultStats.value?.standard_price_stats) return []
  
  let allStats = []
  
  // 添加标准价格统计
  if (resultStats.value?.standard_price_stats) {
    allStats = Object.entries(resultStats.value.standard_price_stats)
      .map(([unit, stats]) => ({
        unit,
        ...stats
      }))
  }
  
  // 添加标准价格2统计
  if (resultStats.value?.standard_price2_stats) {
    const price2Stats = Object.entries(resultStats.value.standard_price2_stats)
      .map(([unit, stats]) => ({
        unit: unit + ' (第二单位)',
        ...stats
      }))
    allStats = [...allStats, ...price2Stats]
  }
  
  return allStats
})

const confidenceDistributionData = computed(() => {
  if (!resultStats.value?.confidence_distribution) return []
  
  const total = resultStats.value.total_products || 1
  return Object.entries(resultStats.value.confidence_distribution)
    .map(([level, count]) => ({
      level,
      count,
      percentage: count / total
    }))
    .sort((a, b) => {
      const levelOrder = { '很高': 0, '高': 1, '中等': 2, '低': 3, '很低': 4 }
      return levelOrder[a.level] - levelOrder[b.level]
    })
})

// 提取方式统计数据
const extractMethodData = computed(() => {
  if (!resultStats.value?.extract_method_distribution) return []
  
  const total = resultStats.value.total_products || 1
  return Object.entries(resultStats.value.extract_method_distribution)
    .map(([method, count]) => ({
      method: method === 'rule' ? '规则提取' : method === 'ai' ? 'AI提取' : method,
      originalMethod: method,
      count,
      percentage: count / total
    }))
    .sort((a, b) => b.count - a.count)
})

// 不同提取方式的置信度统计
const extractMethodConfidenceStats = computed(() => {
  if (!resultStats.value || !allRows.value.length) return []
  
  // 按提取方式分组
  const methodGroups = {}
  
  allRows.value.forEach(row => {
    if (!row.extract_method || !row.confidence_score) return
    
    if (!methodGroups[row.extract_method]) {
      methodGroups[row.extract_method] = {
        confidences: [],
        count: 0
      }
    }
    
    methodGroups[row.extract_method].confidences.push(parseFloat(row.confidence_score))
    methodGroups[row.extract_method].count++
  })
  
  // 计算每种方式的平均值和中位数
  return Object.entries(methodGroups).map(([method, data]) => {
    // 排序用于计算中位数
    const sorted = [...data.confidences].sort((a, b) => a - b)
    const mid = Math.floor(sorted.length / 2)
    const medianConfidence = sorted.length % 2 === 0
      ? (sorted[mid - 1] + sorted[mid]) / 2
      : sorted[mid]
    
    const sum = data.confidences.reduce((a, b) => a + b, 0)
    
    return {
      method: method === 'rule' ? '规则提取' : method === 'ai' ? 'AI提取' : method,
      originalMethod: method,
      count: data.count,
      avgConfidence: data.confidences.length ? sum / data.confidences.length : 0,
      medianConfidence
    }
  }).sort((a, b) => a.originalMethod.localeCompare(b.originalMethod))
})

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(totalRows.value / pageSize.value)
})

// 页面加载时获取数据
onMounted(async () => {
  await fetchDbBrands()
  fetchResultPreview()
})
</script>

<style scoped>
.result-preview-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.sheet-selector {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.sheet-label {
  margin-right: 10px;
  font-weight: bold;
}

.pagination {
  margin-top: 20px;
  margin-bottom: 20px;
}

.top-pagination {
  margin-bottom: 10px;
  margin-top: 0;
  display: flex;
  justify-content: center;
}

.bottom-pagination {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.pagination-actions {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
}

.page-info {
  font-size: 14px;
  color: #606266;
  min-width: 80px;
  text-align: center;
}

.stat-title {
  margin-top: 20px;
  margin-bottom: 10px;
  font-weight: bold;
}

:deep(.high-confidence) {
  background-color: #f0f9eb;
}

:deep(.medium-confidence) {
  background-color: #fdf6ec;
}

:deep(.low-confidence) {
  background-color: #fef0f0;
}

:deep(.very-low-confidence) {
  background-color: #fee;
}

:deep(.cleaned-column) {
  font-weight: bold;
  color: #409eff;
}

:deep(.rule-extraction) {
  background-color: #f0f9eb;
}

:deep(.ai-extraction) {
  background-color: #fdf6ec;
}
</style> 